package com.ddm.service.impl.webImpl;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ddm.entity.webEntity.Regulation;
import com.ddm.mapper.BookmarkMapper;
import com.ddm.mapper.RegulationMapper;
import com.ddm.service.webService.RegulationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 规章制度表 服务实现类
 * </p>
 *
 * @author hpq
 * @since 2025-05-08
 */
@Slf4j
@Service
public class RegulationServiceImpl extends ServiceImpl<RegulationMapper, Regulation> implements RegulationService {

    @Autowired
    private RegulationMapper regulationMapper;

    @Autowired
    private BookmarkMapper bookmarkMapper;


    @Override
    public Boolean add(Regulation regulation) {
        if (regulation == null) {
            return false;
        }
        // 检查规章制度名称
        if (regulation.getName() == null || regulation.getName().trim().isEmpty()) {
            return false;
        }
        // 检查发布日期
        if (regulation.getPublishDate() == null) {
            return false;
        }
        // 检查规章制度链接
        if (regulation.getUrl() == null || regulation.getUrl().trim().isEmpty()) {
            return false;
        }
        // 检查规章制度 PDF 文件路径
        if (regulation.getPdf() == null || regulation.getPdf().trim().isEmpty()) {
            return false;
        }
        // 检查发布部门
        if (regulation.getPublishDepartment() == null || regulation.getPublishDepartment().trim().isEmpty()) {
            return false;
        }
        // 检查生效时间
        if (regulation.getValidTime() == null) {
            return false;
        }
        save(regulation);  // 执行保存
        Regulation savedRegulation = getById(regulation.getId());  // 通过ID查询数据
        return savedRegulation != null;  // 存在即返回true
    }



    @Override
    public Boolean update(Regulation regulation) {
        if (regulation == null || regulation.getId() == null) {
            return false;
        }
        return updateById(regulation);
    }




    @Override
    public Boolean delete(Integer id) {
        if (id == null || id <= 0) {
            return false;
        }
        System.out.println(id );
        return removeById(id);
    }




    @Override
    public Regulation getRegulationById(Integer id) {
        // 实现根据id查询详情逻辑
        return   regulationMapper.selectById(id);
    }




    @Override
    public List<Regulation> getAllRegulations() {
        // 使用 QueryWrapper 查询所有记录，这里没有设置查询条件，意味着查询全量数据
        QueryWrapper<Regulation> queryWrapper = new QueryWrapper<>();
        return regulationMapper.selectList(queryWrapper);
    }



    @Override
    public IPage<Regulation> getRegulationsByPage(Page<Regulation> page, String key) {
        QueryWrapper<Regulation> wrapper = new QueryWrapper<>();
        LambdaQueryWrapper<Regulation> lambdaWrapper = wrapper.lambda();

        // 处理多字段模糊查询（如果key不为空）
        if (key != null && !key.isEmpty()) {
            lambdaWrapper.nested(i -> i
                    .like(Regulation::getName, key)
                    .or().like(Regulation::getPublishDepartment, key)
            );
        }
        lambdaWrapper.orderByDesc(Regulation::getPublishDate);
        return this.page(page, lambdaWrapper);
    }











    @Override
    public IPage<Regulation> getRegulationsByCategoryIds(List<Integer> ids, Page<Regulation> page) {
        if (CollectionUtils.isEmpty(ids)) {
            return new Page<>(); // 返回空分页对象
        }
        // 创建查询条件
        QueryWrapper<Regulation> wrapper = new QueryWrapper<>();
        wrapper.in("id", ids); // 查询ID在列表中的记录
        // 执行分页查询
        return regulationMapper.selectPage(page, wrapper);
    }


    @Override
    public IPage<Regulation> getCollectedRegulationByUserId(Page<Regulation> page, Integer userId, String key) {
        // 打印方法入参，确认分页参数、用户ID和关键词
        log.info("开始查询用户收藏政策规章 | userId: {}, 页码: {}, 每页条数: {}, 关键词: {}",
                userId, page.getCurrent(), page.getSize(), key);

        // 1. 查询用户收藏的所有course_id
        log.info("Step 1: 查询用户[{}]收藏的course_id列表", userId);
        List<Integer> regulationIds = bookmarkMapper.selectRegulationIdsByUserId(userId);
        // 过滤掉null值
        regulationIds = regulationIds.stream()
                .filter(Objects::nonNull) // 保留非null的id
                .collect(Collectors.toList());
        log.info("Step 1结果: 收藏的regulation_id数量为: {}", regulationIds != null ? regulationIds.size() : 0);
        if (!CollectionUtils.isEmpty(regulationIds)) {
            log.info("Step 1详情: 收藏的regulation_id列表: {}", regulationIds);
        }

        // 2. 处理无收藏课程情况，返回包含分页参数的空结果
        if (CollectionUtils.isEmpty(regulationIds)) {
            log.info("Step 2: 用户[{}]无收藏政策法规，返回空分页", userId);
            Page<Regulation> emptyPage = new Page<>(page.getCurrent(), page.getSize());
            emptyPage.setTotal(0);
            return emptyPage;
        }

        // 3. 构造查询条件：先锁定收藏课程范围，再做关键词搜索
        log.info("Step 3: 构造查询条件 | 关键词: {}", key);
        LambdaQueryWrapper<Regulation> lambdaWrapper = new LambdaQueryWrapper<>();
        lambdaWrapper.in(Regulation::getId, regulationIds)
                .last(""); // 关键：清除 MyBatis-Plus 自动添加的 WHERE deleted=0
        log.info("Step 3条件: 已添加收藏政策法规ID范围筛选（共{}个ID）", regulationIds.size());

        if (StrUtil.isNotBlank(key)) {
            lambdaWrapper.nested(i -> i
                    .like(Regulation::getName, key)
                    .or()
                    .like(Regulation::getPublishDepartment, key)
                    .or()
                    .like(Regulation::getLevel,key)
            );
            log.info("Step 3条件: 已添加关键词[{}]的模糊查询（匹配政策名、发布部门、级别）", key);
        } else {
            log.info("Step 3条件: 无关键词，仅查询收藏课程");
        }

        // 4. 分页查询
        log.info("Step 4: 执行分页查询 | SQL条件: {}", lambdaWrapper.getSqlSegment()); // 打印SQL条件片段
        IPage<Regulation> resultPage = baseMapper.selectPage(page, lambdaWrapper);

        // 打印查询结果
        log.info("Step 4结果: 总记录数: {}, 当前页记录数: {}, 页码: {}",
                resultPage.getTotal(),
                resultPage.getRecords().size(),
                resultPage.getCurrent());

        return resultPage;
    }
}